<template>
	<view class="container" :style="{ backgroundColor: pageinfo.bgcolor }">
		<block>
			<dp :pagecontent="pagecontent" :menuindex="menuindex" :latitude="latitude" :longitude="longitude"></dp>
			<!-- <dp-guanggao :guanggaopic="guanggaopic" :guanggaourl="guanggaourl" v-if="isguanggao"></dp-guanggao> -->
			<dp-tabbar :opt="opt" @getmenuindex="getmenuindex"></dp-tabbar>
		</block>
		<scrolltop :isshow="scrolltopshow"></scrolltop>
		<popmsg ref="popmsg"></popmsg>
		<loading v-if="loading"></loading>
	</view>
</template>
<script>
var app = getApp();
export default {
	data() {
		return {
			opt: {},
			loading: false,
			isload: false,
			menuindex: -1,
			pre_url: app.globalData.pre_url, static_url: app.globalData.static_url,
			id: 0,
			pageinfo: [],
			pagecontent: [],
			title: "",
			oglist: "",
			guanggaopic: "",
			guanggaourl: "",
			latitude: '',
			longitude: '',
			area: '',

			sysset: {},
			showlevel: 2,
			show_location: 0,
			curent_address: '',//当前位置: 城市或者收货地址
			arealist: [],
			show_nearbyarea: false,
			ischangeaddress: false,
			nearbyplacelist: [],
			myaddresslist: [],
			isshowalladdress: false,
			placekeyword: '',
			suggestionplacelist: [],
			isguanggao: 0,
			LSindexTab: [],
			LStabList: [],
			LSisTabCanTop: '',
			scrolltopshow: false,
			scrollY: 0
		}
	},
	mounted() {
		let that = this;
		uni.$on('scrollLast', (data) => {
			if (data) {
				that.scrollToTarget(data.target);
			}
		});
	},
	onLoad: function (opt) {
		this.opt = app.getopts(opt);
		//读全局缓存的地区信息
		var cachearea = app.getCache('user_current_area');
		var cacheshowarea = app.getCache('user_current_area_show');
		var cachelongitude = app.getCache('user_current_longitude');
		var cachelatitude = app.getCache('user_current_latitude');
		if (cachearea || cachearea != 1) {
			this.area = cachearea
			this.curent_address = cacheshowarea
			this.latitude = cachelatitude
			this.longitude = cachelongitude
		}
		this.getdata();
		this.LSindexTab = app.globalData.indexTab;
		this.LStabList = app.globalData.tabList;
		this.LSisTabCanTop = app.globalData.isTabCanTop;
		app.globalData.indexTab = [];
		app.globalData.tabList = [];
		app.globalData.isTabCanTop = '';
	},
	onPullDownRefresh: function (e) {
		this.getdata();
	},
	onShareAppMessage: function () {
		return this._sharewx({ title: this.title });
	},
	onShareTimeline: function () {
		var sharewxdata = this._sharewx({ title: this.title });
		var query = (sharewxdata.path).split('?')[1] + '&seetype=circle';
		console.log(sharewxdata)
		console.log(query)
		return {
			title: sharewxdata.title,
			imageUrl: sharewxdata.imageUrl,
			query: query
		}
	},
	onPageScroll: function (e) {
		uni.$emit('onPageScroll', e);
		this.scrollY = e.scrollTop;
		if (this.scrollY > 200) {
			this.scrolltopshow = true;
		}
		if (this.scrollY < 150) {
			this.scrolltopshow = false
		}
	},
	onUnload() {
		app.globalData.indexTab = [];
		app.globalData.tabList = [];
		app.globalData.isTabCanTop = '';
		app.globalData.indexTab = this.LSindexTab;
		app.globalData.tabList = this.LStabList;
		app.globalData.isTabCanTop = this.LSisTabCanTop;
	},
	methods: {
		scrollToTarget(target, options = {}) {
			// let that = this;
			// const { duration = 300, offset = 0 } = options;
			// uni.pageScrollTo({
			// 	scrollTop: target, // 目标位置（单位：px）
			// 	duration,          // 滚动时长（单位：ms）
			// 	success: () => {
			// 		console.log("dp滚动", target)
			// 	},
			// 	fail: (err) => {
			// 	}
			// });
			const {
				duration = 300,
				offset = 0,
				maxRetryTime = 2000,  // 最大重试时间（单位：ms）
				retryInterval = 300   // 重试间隔（单位：ms）
			} = options;

			const startTime = Date.now();
			const that = this;

			// 核心滚动逻辑
			const executeScroll = () => {
				uni.pageScrollTo({
					scrollTop: target,
					duration,
					success: () => {
						// 校验实际滚动位置
						const query = uni.createSelectorQuery().in(that);
						query.selectViewport().scrollOffset(res => {
							const currentPos = res.scrollTop;

							if (Math.abs(currentPos - target) <= offset) {
								console.log("dp滚动成功，当前位置：", currentPos);
							} else {
								handleRetry(); // 未达到目标则重试
							}
						}).exec();
					},
					fail: (err) => {
						console.log("滚动失败：", err);
						handleRetry();
					}
				});
			};

			// 重试控制逻辑
			const handleRetry = () => {
				const elapsed = Date.now() - startTime;
				if (elapsed < maxRetryTime) {
					setTimeout(executeScroll, retryInterval);
				} else {
					console.log("滚动超时，未到达目标位置");
				}
			};

			executeScroll(); // 首次执行
		},

		getdata: function () {
			var that = this;
			var opt = this.opt
			var id = 0;
			if (opt && opt.id) {
				id = opt.id;
			}
			that.loading = true;
			app.get('Index/index', { id: id, latitude: that.latitude, longitude: that.longitude, area: that.area }, function (data) {
				that.loading = false;
				uni.stopPullDownRefresh();
				if (data.status == 2) {
					//付费查看
					app.goto('/pages/pay/pay?id=' + data.payorderid, 'redirect');
					return;
				}
				if (data.status == 1) {
					var pagecontent = data.pagecontent;
					that.title = data.pageinfo.title;
					that.oglist = data.oglist;
					that.guanggaopic = data.guanggaopic;
					that.guanggaourl = data.guanggaourl;
					that.isguanggao = data.isguanggao
					that.pageinfo = data.pageinfo;
					that.pagecontent = data.pagecontent;

					uni.setNavigationBarTitle({
						title: data.pageinfo.title
					});
					that.loaded({ title: that.title });
					if (that.latitude == '' && that.longitude == '' && data.needlocation) {
						app.getLocation(function (res) {
							that.latitude = res.latitude;
							that.longitude = res.longitude;
							that.getdata();
						});
					}
				} else {
					if (data.msg) {
						app.alert(data.msg, function () {
							if (data.url) app.goto(data.url);
						});
					} else if (data.url) {
						app.goto(data.url);
					} else {
						app.alert('您无查看权限');
					}
				}
			});
		}
	}
}
</script>
<style></style>